#!/bin/bash

# Jenkins MCP 服务器启动脚本

set -e

# 脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Go 环境
check_go() {
    if ! command -v go &> /dev/null; then
        print_error "Go is not installed. Please install Go 1.21 or higher."
        exit 1
    fi
    
    GO_VERSION=$(go version | cut -d' ' -f3 | sed 's/go//')
    print_info "Go version: $GO_VERSION"
}

# 检查环境变量
check_env() {
    print_info "检查环境变量..."
    
    # 检查配置文件
    if [ -f "$PROJECT_ROOT/config/config.env" ]; then
        print_info "Loading configuration from config/config.env..."
        set -a
        source "$PROJECT_ROOT/config/config.env"
        set +a
    fi
    
    # 检查必需的环境变量
    if [ -z "$JENKINS_URL" ]; then
        print_error "JENKINS_URL environment variable is required"
        exit 1
    fi
    
    if [ -z "$JENKINS_USERNAME" ]; then
        print_error "JENKINS_USERNAME environment variable is required"
        exit 1
    fi
    
    if [ -z "$JENKINS_TOKEN" ]; then
        print_error "JENKINS_TOKEN environment variable is required"
        exit 1
    fi
    
    print_success "Environment variables check passed"
}

# 安装依赖
install_deps() {
    print_info "Installing dependencies..."
    
    if [ ! -f "$PROJECT_ROOT/src/go.mod" ]; then
        print_error "go.mod not found in src directory."
        exit 1
    fi
    
    cd "$PROJECT_ROOT/src"
    go mod download
    print_success "Dependencies installed"
}

# 构建程序
build() {
    print_info "Building Jenkins MCP server..."
    
    # 创建构建目录
    mkdir -p "$PROJECT_ROOT/bin"
    
    # 切换到源代码目录并构建程序
    cd "$PROJECT_ROOT/src"
    go build -o "$PROJECT_ROOT/bin/jenkins-mcp-server" .
    
    if [ $? -eq 0 ]; then
        print_success "Build completed successfully"
    else
        print_error "Build failed"
        exit 1
    fi
}

# 运行程序
run() {
    print_info "Starting Jenkins MCP server..."
    
    # 显示配置信息
    print_info "Configuration:"
    print_info "  Jenkins URL: $JENKINS_URL"
    print_info "  Username: $JENKINS_USERNAME"
    print_info "  Server Mode: ${SERVER_MODE:-stdio}"
    
    if [ "${SERVER_MODE:-stdio}" = "http" ]; then
        print_info "  HTTP Server: ${SERVER_HOST:-localhost}:${SERVER_PORT:-8080}"
    fi
    
    # 运行程序
    exec "$PROJECT_ROOT/bin/jenkins-mcp-server"
}

# 直接运行（不构建）
run_direct() {
    print_info "Running Jenkins MCP server directly..."
    
    # 显示配置信息
    print_info "Configuration:"
    print_info "  Jenkins URL: $JENKINS_URL"
    print_info "  Username: $JENKINS_USERNAME"
    print_info "  Server Mode: ${SERVER_MODE:-stdio}"
    
    if [ "${SERVER_MODE:-stdio}" = "http" ]; then
        print_info "  HTTP Server: ${SERVER_HOST:-localhost}:${SERVER_PORT:-8080}"
    fi
    
    # 直接运行
    cd "$PROJECT_ROOT/src"
    exec go run .
}

# 运行测试
test() {
    print_info "Running tests..."
    
    cd "$PROJECT_ROOT/src"
    go test -v ./...
    
    if [ $? -eq 0 ]; then
        print_success "All tests passed"
    else
        print_error "Some tests failed"
        exit 1
    fi
}

# 清理
clean() {
    print_info "Cleaning up..."
    
    rm -rf "$PROJECT_ROOT/bin/"
    cd "$PROJECT_ROOT/src"
    go clean
    
    print_success "Cleanup completed"
}

# 显示帮助
show_help() {
    cat << EOF
Jenkins MCP 服务器启动脚本

用法: $0 [COMMAND]

命令:
    start       构建并启动服务器 (默认)
    run         直接运行服务器 (不构建)
    build       只构建程序
    test        运行测试
    clean       清理构建文件
    help        显示此帮助信息

环境变量:
    JENKINS_URL      Jenkins 服务器地址 (必需)
    JENKINS_USERNAME Jenkins 用户名 (必需)
    JENKINS_TOKEN    Jenkins API Token (必需)
    JENKINS_TIMEOUT  请求超时时间 (默认: 30s)
    SERVER_MODE      服务器模式 (stdio/http, 默认: stdio)
    SERVER_HOST      HTTP 服务器地址 (默认: localhost)
    SERVER_PORT      HTTP 服务器端口 (默认: 8080)

示例:
    # 使用 stdio 模式启动 (默认)
    $0 start

    # 使用 HTTP 模式启动
    SERVER_MODE=http $0 start

    # 直接运行 (开发模式)
    $0 run

    # 运行测试
    $0 test

EOF
}

# 主函数
main() {
    local command=${1:-start}
    
    case $command in
        start)
            check_go
            check_env
            install_deps
            build
            run
            ;;
        run)
            check_go
            check_env
            install_deps
            run_direct
            ;;
        build)
            check_go
            install_deps
            build
            ;;
        test)
            check_go
            install_deps
            test
            ;;
        clean)
            clean
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_error "Unknown command: $command"
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@" 